import Joi from 'joi'
import { pathParams } from '../index.js'
import { GithubAuthV3Service } from './github-auth-service.js'
import { documentation, httpErrorsFor } from './github-helpers.js'

const schema = Joi.object({
  color: Joi.string().hex().required(),
}).required()

export default class GithubLabels extends GithubAuthV3Service {
  static category = 'issue-tracking'
  static route = { base: 'github/labels', pattern: ':user/:repo/:name' }
  static openApi = {
    '/github/labels/{user}/{repo}/{name}': {
      get: {
        summary: 'GitHub labels',
        description: documentation,
        parameters: pathParams(
          {
            name: 'user',
            example: 'atom',
          },
          {
            name: 'repo',
            example: 'atom',
          },
          {
            name: 'name',
            example: 'help-wanted',
          },
        ),
      },
    },
  }

  static defaultBadgeData = { label: ' ' }

  static render({ name, color }) {
    return {
      message: name,
      color,
    }
  }

  async fetch({ user, repo, name }) {
    return this._requestJson({
      url: `/repos/${user}/${repo}/labels/${name}`,
      schema,
      httpErrors: httpErrorsFor('repo or label not found'),
    })
  }

  async handle({ user, repo, name }) {
    const { color } = await this.fetch({ user, repo, name })
    return this.constructor.render({ name, color })
  }
}
